import React, { useState, useRef, KeyboardEvent, useEffect } from 'react';
import {
  Box,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  IconButton,
  Menu,
  MenuItem,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Typography,
  CircularProgress,
  Divider,
  Tooltip,
  ListItemButton,
  Paper,
  InputAdornment,
  Collapse,
  ClickAwayListener,
} from '@mui/material';
import {
  ExpandMore,
  AddCircle,
  FolderOpen,
  InsertDriveFile,
  Add,
  MoreVert,
  ChevronRight,
  Edit,
  Delete,
  ArrowUpward,
  ArrowDownward,
  BookOutlined,
  MenuBook,
  ImportContacts,
  DriveFileRenameOutline,
  Search,
  FilterList,
  SaveAlt,
  ContentCopy,
  ContentCut,
  ContentPaste,
  Check,
  Clear,
} from '@mui/icons-material';
import { styled } from '@mui/material/styles';
import { useNovel } from '../../context/NovelContext.tsx';
import { ItemType, TreeItem } from '../../types/novel.ts';
import { DragDropContext, Droppable, Draggable, DropResult } from 'react-beautiful-dnd';
import { useFileSync } from '../../hooks/fileSystem/index.ts';

// 改变样式组件的定义方式，使用普通样式而不是styled components
const titleStyles = {
  novel: {
    fontWeight: 'bold',
    color: 'primary.dark',
    cursor: 'pointer',
    '&:hover': {
      textDecoration: 'underline',
    },
  },
  volume: {
    fontWeight: 500,
    color: 'secondary.dark',
    cursor: 'pointer',
    '&:hover': {
      textDecoration: 'underline',
    },
  },
  chapter: {
    color: 'text.primary',
    cursor: 'pointer',
    '&:hover': {
      textDecoration: 'underline',
    },
  }
};

interface FileTreeProps {
  onSelectItem?: (item: TreeItem) => void;
}

const FileTree: React.FC<FileTreeProps> = ({ onSelectItem }) => {
  const {
    novels,
    currentItem,
    setCurrentItem,
    addNovel,
    addVolume,
    addChapter,
    updateItem,
    deleteItem,
    isLoading,
    moveItemUp,
    moveItemDown,
    setNovels,
  } = useNovel();

  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
  const [contextMenu, setContextMenu] = useState<{
    mouseX: number;
    mouseY: number;
    item: TreeItem;
  } | null>(null);

  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogMode, setDialogMode] = useState<'novel' | 'volume' | 'chapter' | 'move'>('novel');
  const [dialogParentId, setDialogParentId] = useState<string>('');
  const [newItemName, setNewItemName] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [moveTargetId, setMoveTargetId] = useState<string>('');

  // 剪切板相关状态
  const [clipboard, setClipboard] = useState<{ item: TreeItem, action: 'copy' | 'cut' } | null>(null);

  // 添加重命名对话框状态
  const [renameDialogOpen, setRenameDialogOpen] = useState(false);
  const [itemToRename, setItemToRename] = useState<TreeItem | null>(null);
  const [newItemNameForRename, setNewItemNameForRename] = useState('');

  const { syncState } = useFileSync();

  // 监听小说列表变化，自动展开新导入的小说
  useEffect(() => {
    if (novels.length > 0) {
      // 找出最新添加的小说
      const latestNovel = novels[novels.length - 1];
      if (latestNovel) {
        // 自动展开新导入的小说
        setExpanded(prev => ({
          ...prev,
          [latestNovel.id]: true
        }));

        // 如果小说有卷，也展开第一个卷
        if (latestNovel.children && latestNovel.children.length > 0) {
          const firstVolume = latestNovel.children[0];
          setExpanded(prev => ({
            ...prev,
            [firstVolume.id]: true
          }));
        }
      }
    }
  }, [novels.length]);

  // 当自动导入结果变化时，自动展开根节点
  useEffect(() => {
    if (syncState.autoImportResult?.success && syncState.autoImportResult.novel) {
      const novelId = syncState.autoImportResult.novel.id;
      setExpanded(prev => ({
        ...prev,
        [novelId]: true
      }));
    }
  }, [syncState.autoImportResult]);

  // 处理展开/折叠
  const handleToggle = (id: string) => {
    setExpanded(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  };

  // 处理项目点击
  const handleItemClick = (item: TreeItem) => {
    // 只有章节可以被选中和编辑
    if (item.type === ItemType.CHAPTER) {
      setCurrentItem(item);
      if (onSelectItem) onSelectItem(item);
    } else {
      // 如果点击的是卷或整本，则切换展开/折叠状态
      handleToggle(item.id);
    }
  };

  // 打开上下文菜单
  const handleContextMenu = (event: React.MouseEvent, item: TreeItem) => {
    event.preventDefault();
    event.stopPropagation();
    setContextMenu({
      mouseX: event.clientX - 2,
      mouseY: event.clientY - 4,
      item
    });
  };

  // 关闭上下文菜单
  const handleCloseContextMenu = () => {
    setContextMenu(null);
  };

  // 打开新增对话框
  const handleOpenDialog = (mode: 'novel' | 'volume' | 'chapter' | 'move', parentId?: string) => {
    setDialogMode(mode);
    if (parentId) {
      setDialogParentId(parentId);
    }

    setNewItemName('');
    setDialogOpen(true);
    handleCloseContextMenu();
  };

  // 关闭对话框
  const handleCloseDialog = () => {
    setDialogOpen(false);
  };

  // 处理新增项目
  const handleAddItem = () => {
    if (!newItemName.trim()) {
      return;
    }

    switch (dialogMode) {
      case 'novel':
        addNovel(newItemName);
        break;
      case 'volume':
        addVolume(dialogParentId, newItemName);
        // 自动展开父项
        setExpanded(prev => ({
          ...prev,
          [dialogParentId]: true
        }));
        break;
      case 'chapter':
        addChapter(dialogParentId, newItemName);
        // 自动展开父项
        setExpanded(prev => ({
          ...prev,
          [dialogParentId]: true
        }));
        break;
    }

    handleCloseDialog();
  };

  // 处理删除项目
  const handleDeleteItem = (id: string) => {
    if (window.confirm('确定要删除该项吗？相关内容也会被删除，此操作无法撤销。')) {
      deleteItem(id);
      // 如果删除的是当前选中项，清除选中状态
      if (currentItem && currentItem.id === id) {
        setCurrentItem(null);
      }
    }
    handleCloseContextMenu();
  };

  // 复制项目到剪贴板
  const handleCopyItem = (item: TreeItem) => {
    setClipboard({
      item: JSON.parse(JSON.stringify(item)), // 深拷贝
      action: 'copy'
    });
    handleCloseContextMenu();
  };

  // 剪切项目到剪贴板
  const handleCutItem = (item: TreeItem) => {
    setClipboard({
      item: JSON.parse(JSON.stringify(item)),
      action: 'cut'
    });
    handleCloseContextMenu();
  };

  // 粘贴项目
  const handlePasteItem = (targetId: string, targetType: ItemType) => {
    if (!clipboard) return;

    const { item, action } = clipboard;

    // 根据目标类型决定如何粘贴
    if (targetType === ItemType.NOVEL) {
      // 只能粘贴卷到小说中
      if (item.type === ItemType.VOLUME) {
        // 创建新卷（复制的卷或移动的卷）
        const newName = action === 'copy' ? `${item.name} (副本)` : item.name;
        const newVolumeId = addVolume(targetId, newName);

        // 如果卷中有章节，也需要复制/移动
        if (item.children && item.children.length > 0) {
          item.children.forEach(chapter => {
            if (chapter.type === ItemType.CHAPTER) {
              const newChapterName = action === 'copy' ? `${chapter.name} (副本)` : chapter.name;
              addChapter(newVolumeId, newChapterName);
            }
          });
        }

        // 如果是剪切操作，删除原始卷
        if (action === 'cut') {
          deleteItem(item.id);
          // 清空剪贴板
          setClipboard(null);
        }
      }
    } else if (targetType === ItemType.VOLUME) {
      // 只能粘贴章节到卷中
      if (item.type === ItemType.CHAPTER) {
        // 创建新章节（复制的章节或移动的章节）
        const newName = action === 'copy' ? `${item.name} (副本)` : item.name;
        addChapter(targetId, newName);

        // 如果是剪切操作，删除原始章节
        if (action === 'cut') {
          deleteItem(item.id);
          // 清空剪贴板
          setClipboard(null);
        }
      }
    }

    handleCloseContextMenu();
  };

  // 修改 renderTreeItems 函数，重新设计拖拽结构
  const renderTreeItems = (items: TreeItem[] | undefined, parentId: string = 'root', parentType: ItemType = ItemType.NOVEL) => {
    if (!items || items.length === 0) {
      return null;
    }

    // 确定当前容器可以接收的元素类型
    // 根级别只接收整本小说，小说只能接收卷，卷只能接收章节
    let droppableType = "novel-container"; // 默认为根级别，接收小说

    if (parentId !== 'root') {
      // 非根级别，根据父级类型确定
      droppableType = parentType === ItemType.NOVEL ? "volume-container" : "chapter-container";
    }

    return (
      <Droppable
        droppableId={parentId}
        type={droppableType}
        // 只有小说和卷才能接收拖拽，其他类型禁用拖拽放置
        isDropDisabled={parentType !== ItemType.NOVEL && parentType !== ItemType.VOLUME}
      >
        {(provided, snapshot) => (
          <List
            dense
            disablePadding
            ref={provided.innerRef}
            {...provided.droppableProps}
            sx={{
              backgroundColor: snapshot.isDraggingOver ?
                (parentType === ItemType.NOVEL ? 'rgba(63, 81, 181, 0.08)' :
                  parentType === ItemType.VOLUME ? 'rgba(156, 39, 176, 0.08)' : 'transparent') :
                'transparent',
              borderRadius: '4px',
              transition: 'background-color 0.2s ease',
              // 添加边框以便清晰显示放置区域
              border: snapshot.isDraggingOver ?
                (parentType === ItemType.NOVEL ? '1px dashed #3f51b5' :
                  parentType === ItemType.VOLUME ? '1px dashed #9c27b0' : 'none') :
                'none',
              minHeight: '8px', // 确保空容器也有高度可以拖入
            }}
          >
            {items.map((item, index) => {
              const hasChildren = item.children && item.children.length > 0;
              const isExpanded = expanded[item.id] || false;
              const isSelected = currentItem && currentItem.id === item.id;

              let icon;
              switch (item.type) {
                case ItemType.NOVEL:
                  icon = <MenuBook color="primary" />;
                  break;
                case ItemType.VOLUME:
                  icon = <ImportContacts color="secondary" />;
                  break;
                case ItemType.CHAPTER:
                  icon = <InsertDriveFile />;
                  break;
              }

              // 决定当前项目的拖拽类型
              // 卷只能拖到小说下，章节只能拖到卷下
              const draggableType = item.type === ItemType.VOLUME ? "volume-container" : "chapter-container";

              // 小说不可拖拽，编辑状态下也禁用拖拽
              const isDragDisabled = item.type === ItemType.NOVEL;

              return (
                <React.Fragment key={item.id}>
                  {/* 只有非小说项目可拖拽 */}
                  {item.type !== ItemType.NOVEL ? (
                    <Draggable
                      draggableId={item.id}
                      index={index}
                      isDragDisabled={isDragDisabled}
                    >
                      {(provided, snapshot) => (
                        <>
                          <ListItemButton
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                            onClick={() => !isDragDisabled && handleItemClick(item)}
                            selected={isSelected || false}
                            onContextMenu={(e) => !isDragDisabled && handleContextMenu(e, item)}
                            sx={{
                              pl: item.type === ItemType.VOLUME ? 2 : item.type === ItemType.CHAPTER ? 4 : 0,
                              bgcolor: snapshot.isDragging ? 'action.hover' :
                                isSelected ? 'action.selected' : 'transparent',
                              '&:hover': {
                                bgcolor: 'action.hover',
                              },
                              padding: '4px 8px',
                              borderRadius: '4px',
                              mb: 0.5,
                              cursor: snapshot.isDragging ? 'grabbing' : 'grab',
                              userSelect: 'none',
                              borderLeft: item.type === ItemType.VOLUME ? '3px solid #9c27b0' :
                                item.type === ItemType.CHAPTER ? '3px solid #2196f3' : 'none',
                              // 拖拽时增加阴影效果
                              boxShadow: snapshot.isDragging ? '0 2px 8px rgba(0,0,0,0.2)' : 'none',
                              zIndex: snapshot.isDragging ? 999 : 'auto',
                            }}
                          >
                            <ItemContent
                              item={item}
                              hasChildren={hasChildren}
                              isExpanded={isExpanded}
                              handleToggle={handleToggle}
                              handleContextMenu={handleContextMenu}
                              icon={icon}
                              snapshot={snapshot}
                            />
                          </ListItemButton>

                          {hasChildren && (
                            <Collapse in={isExpanded} timeout="auto" unmountOnExit>
                              <Box sx={{ ml: 2 }}>
                                {renderTreeItems(item.children, item.id, item.type)}
                              </Box>
                            </Collapse>
                          )}

                          {/* 为空卷添加可拖放区域 */}
                          {!hasChildren && item.type === ItemType.VOLUME && isExpanded && (
                            <Collapse in={isExpanded} timeout="auto" unmountOnExit>
                              <Box sx={{ ml: 2 }}>
                                <Droppable
                                  droppableId={item.id}
                                  type="chapter-container"
                                >
                                  {(provided, snapshot) => (
                                    <List
                                      dense
                                      disablePadding
                                      ref={provided.innerRef}
                                      {...provided.droppableProps}
                                      sx={{
                                        backgroundColor: snapshot.isDraggingOver ? 'rgba(156, 39, 176, 0.08)' : 'rgba(0, 0, 0, 0.03)',
                                        borderRadius: '4px',
                                        transition: 'background-color 0.2s ease',
                                        border: snapshot.isDraggingOver ? '1px dashed #9c27b0' : '1px dashed #ccc',
                                        minHeight: '40px', // 增加足够的高度以便于拖拽
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        my: 1,
                                      }}
                                    >
                                      {/* 添加空卷提示文字 */}
                                      {!snapshot.isDraggingOver && (
                                        <Typography variant="caption" color="text.secondary" sx={{ fontStyle: 'italic' }}>
                                          空卷 - 拖拽章节到此处
                                        </Typography>
                                      )}
                                      {snapshot.isDraggingOver && (
                                        <Typography variant="caption" color="secondary" sx={{ fontWeight: 'bold' }}>
                                          放置到此卷
                                        </Typography>
                                      )}
                                      {provided.placeholder}
                                    </List>
                                  )}
                                </Droppable>
                              </Box>
                            </Collapse>
                          )}
                        </>
                      )}
                    </Draggable>
                  ) : (
                    // 小说项目不可拖拽，直接渲染
                    <>
                      <Draggable
                        draggableId={item.id}
                        index={index}
                        isDragDisabled={isDragDisabled}
                      >
                        {(provided, snapshot) => (
                          <>
                            <ListItemButton
                              ref={provided.innerRef}
                              {...provided.draggableProps}
                              {...provided.dragHandleProps}
                              onClick={() => !isDragDisabled && handleItemClick(item)}
                              selected={isSelected || false}
                              onContextMenu={(e) => !isDragDisabled && handleContextMenu(e, item)}
                              sx={{
                                pl: 0,
                                bgcolor: snapshot.isDragging ? 'action.hover' :
                                  isSelected ? 'action.selected' : 'transparent',
                                '&:hover': {
                                  bgcolor: 'action.hover',
                                },
                                padding: '4px 8px',
                                borderRadius: '4px',
                                mb: 0.5,
                                cursor: snapshot.isDragging ? 'grabbing' : 'pointer',
                                userSelect: 'none',
                                // 为小说添加特殊边框
                                borderLeft: '3px solid #3f51b5',
                                // 拖拽时增加阴影效果
                                boxShadow: snapshot.isDragging ? '0 2px 8px rgba(0,0,0,0.2)' : 'none',
                                zIndex: snapshot.isDragging ? 999 : 'auto',
                              }}
                            >
                              <ItemContent
                                item={item}
                                hasChildren={hasChildren}
                                isExpanded={isExpanded}
                                handleToggle={handleToggle}
                                handleContextMenu={handleContextMenu}
                                icon={icon}
                                snapshot={snapshot}
                              />
                            </ListItemButton>

                            {hasChildren && (
                              <Collapse in={isExpanded} timeout="auto" unmountOnExit>
                                <Box sx={{ ml: 2 }}>
                                  {renderTreeItems(item.children, item.id, item.type)}
                                </Box>
                              </Collapse>
                            )}

                            {/* 为空小说添加可拖放区域 */}
                            {!hasChildren && item.type === ItemType.NOVEL && isExpanded && (
                              <Collapse in={isExpanded} timeout="auto" unmountOnExit>
                                <Box sx={{ ml: 2 }}>
                                  <Droppable
                                    droppableId={item.id}
                                    type="volume-container"
                                  >
                                    {(provided, snapshot) => (
                                      <List
                                        dense
                                        disablePadding
                                        ref={provided.innerRef}
                                        {...provided.droppableProps}
                                        sx={{
                                          backgroundColor: snapshot.isDraggingOver ? 'rgba(63, 81, 181, 0.08)' : 'rgba(0, 0, 0, 0.03)',
                                          borderRadius: '4px',
                                          transition: 'background-color 0.2s ease',
                                          border: snapshot.isDraggingOver ? '1px dashed #3f51b5' : '1px dashed #ccc',
                                          minHeight: '50px', // 增加足够的高度以便于拖拽
                                          display: 'flex',
                                          alignItems: 'center',
                                          justifyContent: 'center',
                                          my: 1,
                                        }}
                                      >
                                        {!snapshot.isDraggingOver && (
                                          <Typography variant="caption" color="text.secondary" sx={{ fontStyle: 'italic' }}>
                                            空小说 - 拖拽卷到此处
                                          </Typography>
                                        )}
                                        {snapshot.isDraggingOver && (
                                          <Typography variant="caption" color="primary" sx={{ fontWeight: 'bold' }}>
                                            放置到此小说
                                          </Typography>
                                        )}
                                        {provided.placeholder}
                                      </List>
                                    )}
                                  </Droppable>
                                </Box>
                              </Collapse>
                            )}
                          </>
                        )}
                      </Draggable>
                    </>
                  )}
                </React.Fragment>
              );
            })}
            {provided.placeholder}
          </List>
        )}
      </Droppable>
    );
  };

  // 抽取项目内容为单独组件，减少重复代码
  const ItemContent = ({
    item,
    hasChildren,
    isExpanded,
    handleToggle,
    handleContextMenu,
    icon,
    snapshot
  }: any) => {
    return (
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          width: '100%',
          '& > *': {
            pointerEvents: snapshot?.isDragging ? 'none' : 'auto',
          },
        }}
      >
        {hasChildren && (
          <IconButton
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              handleToggle(item.id);
            }}
            sx={{ mr: 0.5, p: 0.5 }}
          >
            {isExpanded ? <ExpandMore fontSize="small" /> : <ChevronRight fontSize="small" />}
          </IconButton>
        )}

        {!hasChildren && <Box sx={{ width: 28 }} />}

        <ListItemIcon sx={{ minWidth: 32 }}>
          {icon}
        </ListItemIcon>

        <ListItemText
          primary={
            <Typography
              variant="body2"
              noWrap
              sx={{
                ...(item.type === ItemType.NOVEL
                  ? titleStyles.novel
                  : item.type === ItemType.VOLUME
                    ? titleStyles.volume
                    : titleStyles.chapter),
                textIndent: 0,
                paddingLeft: 0,
                whiteSpace: 'nowrap',
              }}
              title={item.name}
            >
              {item.name}
            </Typography>
          }
          sx={{
            margin: 0,
            padding: 0,
            '.MuiListItemText-primary': {
              display: 'flex',
              textIndent: 0,
              paddingLeft: 0,
              margin: 0
            }
          }}
        />

        <IconButton
          size="small"
          onClick={(e) => {
            e.stopPropagation();
            handleContextMenu(e, item);
          }}
          sx={{ p: 0.5 }}
        >
          <MoreVert fontSize="small" />
        </IconButton>
      </Box>
    );
  };

  // 简化和优化handleDragEnd函数
  const handleDragEnd = (result: DropResult) => {
    const { source, destination, draggableId, type } = result;

    // 如果没有目标位置或拖回原位置，不做任何操作
    if (!destination) {
      return;
    }

    // 同位置不操作
    if (source.droppableId === destination.droppableId && source.index === destination.index) {
      return;
    }

    // 根据拖拽类型确定处理逻辑
    try {
      if (type === "volume-container") {
        // 处理卷的拖拽 - 必须确保目标是小说级别且不是root级别
        const sourceNovel = findItemById(novels, source.droppableId);
        const destNovel = findItemById(novels, destination.droppableId);

        // 验证源和目标都是小说级别，且目标不是root
        if (!sourceNovel || !destNovel ||
          (sourceNovel.id !== 'root' && sourceNovel.type !== ItemType.NOVEL) ||
          destNovel.type !== ItemType.NOVEL) {
          console.error('卷只能在小说内部拖拽，不能与小说同级');
          return;
        }

        // 获取要移动的卷
        const volumeIndex = source.index;
        const sourceChildren = sourceNovel.id === 'root' ? novels : sourceNovel.children || [];

        if (volumeIndex >= sourceChildren.length) {
          console.error('源索引超出范围');
          return;
        }

        const volumeToMove = sourceChildren[volumeIndex];

        if (volumeToMove.type !== ItemType.VOLUME) {
          console.error('只能拖拽卷类型');
          return;
        }

        // 从源位置移除
        sourceChildren.splice(volumeIndex, 1);

        // 获取目标容器的子数组
        const destChildren = destNovel.id === 'root' ? novels : destNovel.children || [];

        // 将卷插入目标位置
        destChildren.splice(destination.index, 0, volumeToMove);

        // 更新卷的parentId
        volumeToMove.parentId = destNovel.id;

        // 更新状态
        setNovels([...novels]);
      }
      else if (type === "chapter-container") {
        // 处理章节的拖拽 - 必须确保目标是卷级别
        const sourceVolume = findItemById(novels, source.droppableId);
        const destVolume = findItemById(novels, destination.droppableId);

        // 验证源和目标都是卷级别
        if (!sourceVolume || !destVolume ||
          sourceVolume.type !== ItemType.VOLUME ||
          destVolume.type !== ItemType.VOLUME) {
          console.error('章节只能在卷级别拖拽');
          return;
        }

        // 获取要移动的章节
        if (!sourceVolume.children || source.index >= sourceVolume.children.length) {
          console.error('源索引超出范围');
          return;
        }

        const chapterToMove = sourceVolume.children[source.index];

        if (chapterToMove.type !== ItemType.CHAPTER) {
          console.error('只能拖拽章节类型');
          return;
        }

        // 从源位置移除
        sourceVolume.children.splice(source.index, 1);

        // 确保目标卷有children数组
        if (!destVolume.children) {
          destVolume.children = [];
        }

        // 将章节插入目标位置
        destVolume.children.splice(destination.index, 0, chapterToMove);

        // 更新章节的parentId
        chapterToMove.parentId = destVolume.id;

        // 更新状态
        setNovels([...novels]);
      }
      else if (type === "novel-container") {
        // 处理整本小说的拖拽 - 只能在根级别移动顺序
        if (source.droppableId !== 'root' || destination.droppableId !== 'root') {
          console.error('小说只能在根级别内移动顺序');
          return;
        }

        // 移动整本小说
        const [movedNovel] = novels.splice(source.index, 1);
        novels.splice(destination.index, 0, movedNovel);

        // 更新状态
        setNovels([...novels]);
      }
    } catch (error) {
      console.error('拖拽处理错误:', error);
    }
  };

  // 修改findItemById函数，优化root处理
  const findItemById = (items: TreeItem[], id: string): TreeItem | null => {
    // 特殊处理根级别
    if (id === 'root') {
      return {
        id: 'root',
        name: 'root',
        type: ItemType.NOVEL,
        children: items
      };
    }

    // 递归查找
    for (const item of items) {
      if (item.id === id) {
        return item;
      }

      if (item.children && item.children.length > 0) {
        const found = findItemById(item.children, id);
        if (found) {
          return found;
        }
      }
    }

    return null;
  };

  // 搜索过滤项目
  const filterItems = (items: TreeItem[]): TreeItem[] => {
    if (!searchQuery) return items;

    return items.filter(item => {
      const matchesQuery = item.name.toLowerCase().includes(searchQuery.toLowerCase());

      // 递归检查子项
      let filteredChildren: TreeItem[] = [];
      if (item.children && item.children.length) {
        filteredChildren = filterItems(item.children);
      }

      // 如果有匹配的子项，创建一个新的项目包含这些子项
      if (filteredChildren.length) {
        return true;
      }

      return matchesQuery;
    });
  };

  // 过滤后的项目列表
  const filteredNovels = filterItems(novels);

  // 修改handleStartEdit函数，使用对话框而不是内联编辑
  const handleStartEdit = (item: TreeItem) => {
    setItemToRename(item);
    setNewItemNameForRename(item.name);
    setRenameDialogOpen(true);
    handleCloseContextMenu();
  };

  // 处理重命名对话框关闭
  const handleCloseRenameDialog = () => {
    setRenameDialogOpen(false);
    setItemToRename(null);
  };

  // 保存重命名
  const handleSaveRename = () => {
    if (itemToRename && newItemNameForRename.trim()) {
      updateItem(itemToRename.id, { name: newItemNameForRename.trim() });
    }
    setRenameDialogOpen(false);
    setItemToRename(null);
  };

  return (
    <DragDropContext
      onDragEnd={handleDragEnd}
      // 添加开始拖拽处理
      onDragStart={(start) => {
        // 展开目标容器，方便用户看到放置位置
        const parentId = start.source.droppableId;
        if (parentId !== 'root') {
          setExpanded(prev => ({
            ...prev,
            [parentId]: true
          }));
        }
      }}
    >
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
          padding: (theme) => theme.spacing(1),
          backgroundColor: '#f8f9fa',
          borderRight: '1px solid #e0e0e0'
        }}
      >
        {/* 头部标题 */}
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: (theme) => theme.spacing(1),
            padding: (theme) => theme.spacing(1),
            borderBottom: '1px solid #e0e0e0'
          }}
        >
          <Typography variant="h6" sx={{ fontSize: '1.1rem' }}>
            项目结构
          </Typography>
          <IconButton
            size="small"
            onClick={() => handleOpenDialog('novel')}
            aria-label="创建新小说"
          >
            <Add />
          </IconButton>
        </Box>

        {/* 搜索框 */}
        <Paper
          elevation={0}
          sx={{
            padding: (theme) => theme.spacing(0.5, 1),
            display: 'flex',
            alignItems: 'center',
            marginBottom: (theme) => theme.spacing(1)
          }}
        >
          <InputAdornment position="start" sx={{ mr: 1 }}>
            <Search fontSize="small" />
          </InputAdornment>
          <TextField
            size="small"
            variant="standard"
            placeholder="搜索..."
            fullWidth
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            InputProps={{
              disableUnderline: true,
            }}
          />
          {searchQuery && (
            <IconButton size="small" onClick={() => setSearchQuery('')}>
              <Delete fontSize="small" />
            </IconButton>
          )}
        </Paper>

        {/* 树内容 */}
        <Box
          sx={{
            flexGrow: 1,
            overflow: 'auto',
            padding: (theme) => theme.spacing(1)
          }}
        >
          {isLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', pt: 2 }}>
              <CircularProgress size={24} />
            </Box>
          ) : (
            renderTreeItems(filteredNovels)
          )}
        </Box>

        {/* 上下文菜单 */}
        <Menu
          open={contextMenu !== null}
          onClose={handleCloseContextMenu}
          anchorReference="anchorPosition"
          anchorPosition={
            contextMenu !== null
              ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
              : undefined
          }
        >
          {/* 小说级别菜单 */}
          {contextMenu?.item.type === ItemType.NOVEL && (
            <>
              <MenuItem onClick={() => handleOpenDialog('volume', contextMenu.item.id)}>
                <ListItemIcon>
                  <AddCircle fontSize="small" />
                </ListItemIcon>
                添加卷
              </MenuItem>
              <MenuItem onClick={() => handleStartEdit(contextMenu.item)}>
                <ListItemIcon>
                  <DriveFileRenameOutline fontSize="small" />
                </ListItemIcon>
                重命名
              </MenuItem>
              <Divider />
              <MenuItem onClick={() => handleCopyItem(contextMenu.item)}>
                <ListItemIcon>
                  <ContentCopy fontSize="small" />
                </ListItemIcon>
                复制
              </MenuItem>
              <MenuItem onClick={() => handleDeleteItem(contextMenu.item.id)}>
                <ListItemIcon>
                  <Delete fontSize="small" color="error" />
                </ListItemIcon>
                删除
              </MenuItem>
            </>
          )}

          {/* 卷级别菜单 */}
          {contextMenu?.item.type === ItemType.VOLUME && (
            <>
              <MenuItem onClick={() => handleOpenDialog('chapter', contextMenu.item.id)}>
                <ListItemIcon>
                  <AddCircle fontSize="small" />
                </ListItemIcon>
                添加章节
              </MenuItem>
              <MenuItem onClick={() => handleStartEdit(contextMenu.item)}>
                <ListItemIcon>
                  <DriveFileRenameOutline fontSize="small" />
                </ListItemIcon>
                重命名
              </MenuItem>
              <Divider />
              <MenuItem onClick={() => handleCopyItem(contextMenu.item)}>
                <ListItemIcon>
                  <ContentCopy fontSize="small" />
                </ListItemIcon>
                复制
              </MenuItem>
              <MenuItem onClick={() => handleCutItem(contextMenu.item)}>
                <ListItemIcon>
                  <ContentCut fontSize="small" />
                </ListItemIcon>
                剪切
              </MenuItem>
              {clipboard &&
                clipboard.item.type === ItemType.CHAPTER && (
                  <MenuItem onClick={() => handlePasteItem(contextMenu.item.id, contextMenu.item.type)}>
                    <ListItemIcon>
                      <ContentPaste fontSize="small" />
                    </ListItemIcon>
                    粘贴
                  </MenuItem>
                )}
              <Divider />
              <MenuItem onClick={() => handleDeleteItem(contextMenu.item.id)}>
                <ListItemIcon>
                  <Delete fontSize="small" color="error" />
                </ListItemIcon>
                删除
              </MenuItem>
            </>
          )}

          {/* 章节级别菜单 */}
          {contextMenu?.item.type === ItemType.CHAPTER && (
            <>
              <MenuItem onClick={() => handleStartEdit(contextMenu.item)}>
                <ListItemIcon>
                  <DriveFileRenameOutline fontSize="small" />
                </ListItemIcon>
                重命名
              </MenuItem>
              <Divider />
              <MenuItem onClick={() => handleCopyItem(contextMenu.item)}>
                <ListItemIcon>
                  <ContentCopy fontSize="small" />
                </ListItemIcon>
                复制
              </MenuItem>
              <MenuItem onClick={() => handleCutItem(contextMenu.item)}>
                <ListItemIcon>
                  <ContentCut fontSize="small" />
                </ListItemIcon>
                剪切
              </MenuItem>
              <Divider />
              <MenuItem onClick={() => handleDeleteItem(contextMenu.item.id)}>
                <ListItemIcon>
                  <Delete fontSize="small" color="error" />
                </ListItemIcon>
                删除
              </MenuItem>
            </>
          )}
        </Menu>

        {/* 添加对话框 (仅用于添加新项目，不再用于重命名) */}
        <Dialog open={dialogOpen} onClose={handleCloseDialog} maxWidth="xs" fullWidth>
          <DialogTitle>
            {dialogMode === 'novel' && '创建新小说'}
            {dialogMode === 'volume' && '添加新卷'}
            {dialogMode === 'chapter' && '添加新章节'}
            {dialogMode === 'move' && '移动项目'}
          </DialogTitle>
          <DialogContent>
            {dialogMode !== 'move' ? (
              <TextField
                autoFocus
                margin="dense"
                label={
                  dialogMode === 'novel' ? '小说名称' :
                    dialogMode === 'volume' ? '卷名称' :
                      dialogMode === 'chapter' ? '章节名称' : '名称'
                }
                type="text"
                fullWidth
                value={newItemName}
                onChange={(e) => setNewItemName(e.target.value)}
                variant="outlined"
                placeholder={
                  dialogMode === 'novel' ? '例：我的小说' :
                    dialogMode === 'volume' ? '例：第一卷' :
                      dialogMode === 'chapter' ? '例：第一章' : ''
                }
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && newItemName.trim()) {
                    e.preventDefault();
                    handleAddItem();
                  }
                }}
              />
            ) : (
              <Typography variant="body2">选择目标位置</Typography>
              // 这里可以添加位置选择UI
            )}
          </DialogContent>
          <DialogActions>
            <Button onClick={handleCloseDialog} color="inherit">取消</Button>
            <Button
              onClick={handleAddItem}
              color="primary"
              disabled={!newItemName.trim()}
            >
              确认
            </Button>
          </DialogActions>
        </Dialog>

        {/* 重命名对话框 */}
        <Dialog
          open={renameDialogOpen}
          onClose={handleCloseRenameDialog}
          maxWidth="xs"
          fullWidth
        >
          <DialogTitle>
            {itemToRename?.type === ItemType.NOVEL ? '编辑小说名称' :
              itemToRename?.type === ItemType.VOLUME ? '编辑卷名称' :
                '编辑章节标题'}
          </DialogTitle>
          <DialogContent>
            <TextField
              autoFocus
              margin="dense"
              label="名称"
              type="text"
              fullWidth
              value={newItemNameForRename}
              onChange={(e) => setNewItemNameForRename(e.target.value)}
              variant="outlined"
              onKeyDown={(e) => {
                if (e.key === 'Enter' && newItemNameForRename.trim()) {
                  e.preventDefault();
                  handleSaveRename();
                }
              }}
            />
          </DialogContent>
          <DialogActions>
            <Button onClick={handleCloseRenameDialog} color="inherit">
              取消
            </Button>
            <Button
              onClick={handleSaveRename}
              color="primary"
              disabled={!newItemNameForRename.trim()}
            >
              保存
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
    </DragDropContext>
  );
};

export default FileTree; 